<template>
  <div
    :class="[
      'relative w-full flex player-wrapper',
      isPortrait ? 'h-screen lazy-video' : '',
      'hidePause'
    ]"
    ref="videoWrapper"
  >
    <!-- 视频播放器 -->
    <video
      v-if="isLoaded"
      id="videoPlayer"
      ref="videoPlayer"
      class="w-full h-full player"
      playsinline
      preload="metadata"
      :poster="poster"
    >
      <!-- <source :src="videoSrc" type="video/mp4" /> -->
      <source :src="videoSrc" />
      浏览器不支持播放该视频
    </video>

    <!-- 加载提示 -->
    <div
      v-if="isLoading"
      class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70 text-white text-sm"
    >
      视频加载中...
    </div>

    <!-- 懒加载提示 -->
    <div
      v-if="!isLoaded"
      class="absolute inset-0 flex items-center justify-center bg-gray-200 text-gray-600 text-sm"
    >
      滚动到此处加载视频...
    </div>
    <AutoPlay @close="play" type="课程" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from "vue";
import Plyr from "plyr";
import "plyr/dist/plyr.css";
import { usePlayerStore } from "@/store/usePlayer";
import { useUserStore } from "@/store/useUserStore";
import { useCourseData } from "@/store/useCourse";
import Hls from "hls.js";
import { useKeyboard } from "@/store/useKeyboard";
import AutoPlay from "@/components/AutoPlay.vue";
const playerStore = usePlayerStore();
const props = defineProps<{
  videoSrc?: string;
  isPortrait?: boolean; // 新增参数，控制横竖屏模式
  poster?: string;
}>();
const emit = defineEmits(["ready", "ended", "start", "update"]);

// Initialize keyboard handling
useKeyboard(
  () => {
    playerStore.setKeyboardVisible(true);
    window.scrollTo(0, 0);
  },
  () => {
    playerStore.setKeyboardVisible(false);
  }
);
const demoVideoSrc =
  "https://zk-cereshop.oss-cn-shenzhen.aliyuncs.com/zkthink/2025-03-22/1ab3e69ee4344cf0bf6e3fd08a6070e8_image-to-video.mp4";
const videoSrc = ref<string>(props.videoSrc || demoVideoSrc);
const videoPlayer = ref<HTMLVideoElement | null>(null);
const videoWrapper = ref<HTMLDivElement | null>(null);
const isLoading = ref<boolean>(false);
const isLoaded = ref<boolean>(false);

// 显示加载提示
const showLoading = () => {
  isLoading.value = true;
};

// 隐藏加载提示
const hideLoading = () => {
  isLoading.value = false;
};

let player: Plyr | null = null;
const courseStore = useCourseData();
const useStore = useUserStore();
const userId = useStore.user.buyerUserId;
const storageKey = `videoProgress_${userId}_${courseStore.courseWatchData.watchRecordId}`;
const videoKey = `progress_max_${userId}_${courseStore.courseWatchData.watchRecordId}`;
let maxProgress = parseFloat(localStorage.getItem(videoKey) || "0");
const initPlyr = () => {
  if (videoPlayer.value) {
    const controls = ["play", "mute"];
    if (!props.isPortrait) {
      controls.push("fullscreen");
    }
    if (playerStore.isControlsEnabled) {
      // controls.push("progress");
    }
    if (
      playerStore.isControlsEnabled ||
      courseStore.courseData.hasShowTime == 1
    ) {
      controls.push("current-time");
    }
    // 判断是否是 HLS 视频流
    if (videoSrc.value && videoSrc.value.endsWith(".m3u8")) {
      if (Hls.isSupported()) {
        showLoading();
        const hls = new Hls({
          debug: import.meta.env.VITE_VIDEO_DEBUG == true
        });
        hls.loadSource(videoSrc.value);
        hls.attachMedia(videoPlayer.value);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          hideLoading();
          player.play();
        });
        // hls.once(Hls.Events.ERROR, (event, data) => {
        //   emit("ended", videoSrc.value);
        //   playerStore.setPlayerEnd();
        // });
      }
      // else if (
      //   videoPlayer.value.canPlayType("application/vnd.apple.mpegurl")
      // ) {
      //   // 直接在浏览器中播放
      //   videoPlayer.value.src = videoSrc.value;
      // }
    }
    // // 处理 HLS 视频流
    // var hls = new Hls();
    // hls.loadSource(videoSrc.value);
    // hls.attachMedia(videoPlayer.value);
    player = new Plyr(videoPlayer.value, {
      // controls: ["play", "current-time", "mute", "progress"],
      controls,
      hideControls: false,
      clickToPlay: false,
      fullscreen: { enabled: !props.isPortrait },
      invertTime: false
    });
    player.poster = props.poster;
    // player.fullscreen.enter();
    player.on("ready", () => {
      emit("ready", maxProgress);
      playerStore.setPlayerStart();
      playerStore.setPlayerReady(maxProgress);
      disableDblclick();
      // player.play();
    });
    player.on("timeupdate", () => {
      if (player) {
        playerStore.setPlayerStart();
        maxProgress = Math.max(maxProgress, player.currentTime);
        saveProgress();
        emit("update", maxProgress);
        playerStore.updateMaxProgress(maxProgress);
        if (import.meta.env.VITE_VIDEO_DEBUG == true) {
          return;
        }
        localStorage.setItem(videoKey, maxProgress.toString());
      }
    });
    // 监听全屏事件
    player.on("enterfullscreen", () => {
      playerStore.setFullScreen(true);
      // 手机按横屏
      document.body.style.transform = "rotate(90deg)";
      document.body.style.transformOrigin = "0 100%";
      document.body.style.width = "100vh";
      document.body.style.height = "100vw";
      document.body.style.position = "fixed";
      document.body.style.overflowX = "hidden";
      document.body.style.top = "-100vw";
    });

    player.on("exitfullscreen", () => {
      playerStore.setFullScreen(false);
      document.body.style.transform = "rotate(0deg)";
      document.body.style.transformOrigin = "0 0";
      document.body.style.width = "100%";
      document.body.style.height = "100%";
      document.body.style.position = "static";
      document.body.style.top = "0";
    });

    // player.on("seeking", () => {
    //   if (player && player.currentTime > maxProgress) {
    //     player.currentTime = maxProgress;
    //   }
    // });

    player.on("ended", () => {
      playerStore.setPlayerEnd();
      emit("ended", videoSrc.value);
    });
  }
};

const initLazyLoad = () => {
  if (videoWrapper.value) {
    if ("IntersectionObserver" in window) {
      const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            isLoaded.value = true;
            observer.unobserve(videoWrapper.value as Element);
          }
        });
      });

      observer.observe(videoWrapper.value);
    } else {
      isLoaded.value = true;
    }
  }
};

// 记录播放进度
const saveProgress = () => {
  if (import.meta.env.VITE_VIDEO_DEBUG == true) {
    return;
  }
  if (videoPlayer.value) {
    localStorage.setItem(storageKey, videoPlayer.value.currentTime.toString());
  }
};

onMounted(() => {
  initLazyLoad();
});

onBeforeUnmount(() => {
  if (player) {
    player.destroy();
  }
});

watch(isLoaded, () => {
  if (isLoaded.value) {
    setTimeout(() => {
      initPlyr();
      const savedTime = localStorage.getItem(storageKey);
      if (videoPlayer.value && savedTime) {
        videoPlayer.value.currentTime = parseFloat(savedTime);
      }
    }, 500);
  }
});
watch(
  () => playerStore.isControlsEnabled,
  (newValue, oldValue) => {
    if (player) {
      if (newValue) {
        player.destroy();
        initPlyr();
      }
    }
  }
);
if (!props.isPortrait) {
  watch(
    () => playerStore.isKeyboardVisible,
    () => {
      // 滚动到最上面
      window.scrollTo(0, 0);
    }
  );
}
watch(
  () => playerStore.isFullScreen,
  isVisible => {
    if (!isVisible) {
      player && player.fullscreen.exit();
    }
  }
);
const disableDblclick = () => {
  document.querySelector(".plyr__video-wrapper").addEventListener(
    "dblclick",
    e => {
      e.preventDefault(); // 阻止全屏默认行为[1,6](@ref)
      e.stopImmediatePropagation(); // 终止事件传递链[4](@ref)
      player?.fullscreen.toggle();
    },
    true
  ); // 使用捕获阶段优先拦截
};
const play = () => {
  player?.play();
};
</script>

<style scoped lang="less">
/* Tailwind CSS 已经提供了大部分样式 */
.player-wrapper > :first-child {
  flex-grow: 1;
}
.hidePause {
  :deep(.plyr--playing) {
    .plyr__controls__item.plyr__control.plyr__control--pressed:first-child {
      display: none;
    }
  }
}
:deep(.plyr__controls) {
  // display: none;
}
</style>
